package com.acwer.oa.web;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * 这个配置不具有实际意义仅解决 activiti7 taskCandidateUser 报错问题
 * 前后端分离思路：使用login登录后利用JWT生成 token 然后使用拦截器解析 header，再验证！
 * @author ZhaoJie
 *
 */
@Configuration
@EnableWebSecurity
public class ApplicationConfiguration extends WebSecurityConfigurerAdapter {

	private Logger logger = LoggerFactory.getLogger(ApplicationConfiguration.class);

//	@Bean
//	public UserDetailsService myUserDetailsService() {
//
//		InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
//
//		// 用户
//		String[][] usersGroupsAndRoles = { { "张三", "123", "ROLE_ACTIVITI_USER" },
//				{ "李四", "password", "ROLE_ACTIVITI_ADMIN" }, { "王五", "password", "ROLE_ACTIVITI_USER" },
//				{ "admin", "123", "ROLE_ACTIVITI_ADMIN" }, };
//
//		for (String[] user : usersGroupsAndRoles) {
//			List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
//			logger.info("> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings
//					+ "]");
//			inMemoryUserDetailsManager.createUser(new User(user[0], passwordEncoder().encode(user[1]),
//					authoritiesStrings.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList())));
//		}
//
//		return inMemoryUserDetailsManager;
//
//	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// authorizeRequests所有security全注解配置实现的开端，表示开始说明需要的权限。
		// 需要的权限分两部分，第一部分是拦截的路径，第二部分访问该路径需要的权限。
		// antMatchers表示拦截什么路径，permitAll任何权限都可以访问，直接放行所有。
		// anyRequest()任何的请求，authenticated认证后才能访问
		// .and().csrf().disable();固定写法，表示使csrf拦截失效。
		// 此配置适用于仅使用security的加密，不使用它的拦截功能
		http.authorizeRequests().antMatchers("/**").permitAll().anyRequest().authenticated().and().csrf().disable();
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

}
